package com.sgx.learning.luban.homework.attributes;

import com.sgx.learning.luban.homework.attributes.ext.ExceptionTable;
import com.sgx.learning.luban.homework.basictype.U2;
import com.sgx.learning.luban.homework.basictype.U4;
import com.sgx.learning.luban.homework.constantpool.ConstantPoolInfo;
import lombok.Data;

import java.io.IOException;
import java.io.InputStream;

@Data
public class Code extends AttributeInfo {

    private short maxStack;
    private short maxLocals;
    private int codeLength;
    private byte[] codes;
    private short exceptionTableLength;
    private ExceptionTable[] tables;
    private short attributeCount;
    private AttributeInfo[] attributeInfos;


    @Override
    public void read(InputStream is, ConstantPoolInfo[] constantPoolInfos) throws IOException {
        this.maxStack = U2.read(is).getValue();
        this.maxLocals = U2.read(is).getValue();
        this.codeLength = U4.read(is).getValue();
        this.codes = new byte[this.codeLength];
        int read = is.read(this.codes);
        if(read == -1) {
            throw new IOException("格式错误");
        }
        this.exceptionTableLength = U2.read(is).getValue();
        if(exceptionTableLength > 0) {
            this.tables = new ExceptionTable[exceptionTableLength];
            for (int i = 0; i < exceptionTableLength; i++) {
                ExceptionTable temp = new ExceptionTable();
                temp.read(is);
                this.tables[i] = temp;
            }
        }
        this.attributeCount = U2.read(is).getValue();
        this.attributeInfos = AttributeHandlerUtils.getAttribute(attributeCount,is,constantPoolInfos);
    }


}
